package com.baseweb.webadmin.controller.app;

import com.baseweb.webadmin.bankpay.util.AcpService;
import com.baseweb.webadmin.bankpay.util.DemoBase;
import com.baseweb.webadmin.bankpay.util.LogUtil;
import com.baseweb.webadmin.bankpay.util.SDKConfig;
import com.baseweb.webadmin.controller.BaseController;
import com.baseweb.webadmin.core.constants.*;
import com.baseweb.webadmin.core.model.bvo.ByUserOrderDetailInfoBvo;
import com.baseweb.webadmin.core.model.bvo.ByUserOrderEvaluatvo;
import com.baseweb.webadmin.core.model.bvo.ByUserOrderInfoBvo;
import com.baseweb.webadmin.core.model.pojo.*;
import com.baseweb.webadmin.core.util.*;
import com.baseweb.webadmin.service.RoleService;
import com.baseweb.webadmin.service.UserOrderService;
import com.baseweb.webadmin.service.UserService;
import net.sf.json.JSONObject;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by zhouxin on 2017/8/22.
 */
@Controller
@RequestMapping(value = "/appApiOrder")
public class OrderAppController  extends BaseController {

    @Autowired
    private UserOrderService userOrderService;

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    /**
     * 查询订单
     * @param userFlag
     * @param statusFlag
     * @param userId
     * @param user
     * @param requestPage
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getMyOrder", method = RequestMethod.POST)
    public Map<String, Object> getMyOrder(@RequestParam(value = "userFlag", required = true) Integer userFlag,
                                          @RequestParam(value = "statusFlag", required = false) Integer statusFlag,
                                          @RequestParam(value = "userId", required = true) Integer userId,
                                          ByUserOrderInfoBvo user,RequestPage requestPage){
        Integer personId = null;
        Integer bizUserId = null;
        Integer status = null;
        Integer payStatus = null;
        if(userFlag == 1){//商家
            bizUserId = userId;
        }else{//个人
            personId = userId;
        }
        if(statusFlag == null){

        }else if(statusFlag == 1){//待付款
            payStatus = -1;
        }else if(statusFlag == 2){//待接单
            payStatus = -2;
            status = 1;
        }else if(statusFlag == 3){//待服务
            payStatus = -2;
            status = 20;
        }else if(statusFlag == 4){//已完成
            payStatus = -2;
            status = 6;
        }else if(statusFlag == 5){//待评价
            user = user == null ? new ByUserOrderInfoBvo() : user;
            user.setUserStars(-1);
            payStatus = -2;
        }else if(statusFlag == 6){//退款单
            status = -3;
        }
        List<ByUserOrderInfoBvo> list = userOrderService.selectOrderListByPage(personId,null,null,bizUserId,status,payStatus,null,null,user,null,requestPage.getStart(), requestPage.getPageSize());
        for(ByUserOrderInfoBvo order : list){
            List<ByUserOrderDetailInfoBvo> detailInfoBvoList = userOrderService.selectOrderDetailListByHtmlPage(null,order.getId(),null,null);
            order.setDetailInfoBvoList(detailInfoBvoList);
        }
        Integer total = userOrderService.selectOrderListByBizUserCount(personId,null,null, bizUserId, status,payStatus,null,null,null,user);
//        ByUserOrderInfoBvo priceLTotal = userOrderService.sumPriceFromOrder(personId,null,null,bizUserId,status,payStatus,null,null,user,null,requestPage.getStart(), requestPage.getPageSize());
        ResultPage result = new ResultPage<>(total == null ? 0 : total,requestPage.getPageSize(),requestPage.getCurPage(),list);
//        Map<String,Object> map = new HashMap<>();
//        map.put("list" , result);
//        map.put("priceLTotal" , priceLTotal);
        return success(result,"订单查询成功");
    }

    /**
     * 更改订单状态
     * @param userFlag
     * @param status
     * @param orderId
     * @param userId
     * @return
     */
    @RequestMapping(value = "/updateOrderStatus")
    @ResponseBody
    public Map<String, Object> updateOrderStatus(@RequestParam(value = "userFlag", required = true) Integer userFlag,
                                    @RequestParam(value = "status",required = true) Integer status,
                                    @RequestParam(value = "orderId",required = true) Integer orderId,
                                    @RequestParam(value = "userId",required = false) Integer userId) {

        try{
            ByUserOrder order = userOrderService.findByUserOrder(orderId);
            User user = userService.selectUserById(userId);
            boolean flag = false;
            //管理员或者商家接单
            if(userFlag == 1 && status == OrderStatus.BIZ_RECEIVE_ORDER.getCode()){
                flag = true;
                User orderUser = userService.selectUserById(order.getUserId());

                //send msg
                Map<String, Object> map = new LinkedHashMap<String, Object>();
                map.put("code", ""+order.getId());

                CommonUtil.sendMessage(orderUser.getMobile(), JSONObject
                        .fromObject(map).toString(), ConfigUtil
                        .getSms_template_code_order_receive());
                String content = user.getCnName() + "已接订单" + orderId;
                ByUserMessage userMessage = new ByUserMessage();
                userMessage.setCreateTime(new DateTime(Calendar.getInstance()));
                userMessage.setContent(content);
                userMessage.setUserId(orderUser.getId());
                userMessage.setOrderId(orderId);
                userService.insertUserMessage(userMessage);
            }else if (userFlag == 2 && userId == order.getUserId().intValue()) {
                flag = true;
                if (status == OrderStatus.CONFIRM_ORDER.getCode()){//用户确认完成订单
                    User bizUser = userService.selectUserById(order.getBizUserId());

                    if (bizUser.getBizDealCount() != null && bizUser.getBizDealCount() > 0) {
                        bizUser.setBizDealCount(bizUser.getBizDealCount() + 1);
                    }else{
                        bizUser.setBizDealCount(1);
                    }

                    BigDecimal commission = BigDecimal.ZERO;
                    Role role = roleService.findRoleByUserIdType(bizUser.getId(),"3");
                    BigDecimal fix = new BigDecimal(role == null ? "0" : role.getRemark());
                    fix = fix.divide(new BigDecimal("100"));
                    if (order.getPayStatus().intValue() == OrderPayStatus.PAY_ALL.getCode()){
                        commission = order.getPrice().multiply(BigDecimal.ONE.subtract(fix));
                    }else if(order.getPayStatus().intValue() == OrderPayStatus.PAY_DEPOSIT.getCode()){
//                            commission = order.getDeposit().subtract(order.getPrice().multiply(BigDecimal.ONE.subtract(fix)));
                        commission = order.getDeposit().subtract(order.getPrice().multiply(fix));
                    }

                    if (bizUser.getMoney() == null || bizUser.getMoney() == BigDecimal.ZERO) {
                        bizUser.setMoney(commission);
                    }else{
                        bizUser.setMoney(bizUser.getMoney().add(commission));
                    }
                    writeMoneyLog(bizUser, MoneyType.PAY_ORDER.getCode(), commission);
                    userService.updateUser(bizUser);
                }else if (status == OrderStatus.CANCEL_NOT_REFUND.getCode()|| status == OrderStatus.CONFIRM_REFUND.getCode()){//用户取消订单
                    //恢复档期
                    userOrderService.deleteScheduleByOrderId(orderId);
                }
            }

            //符合修改规则、商家订单完成、同意退款、拒绝退款
            if(flag || (status == OrderStatus.BIZ_RECEIVE_ORDER.getCode() || status == OrderStatus.CONFIRM_ORDER.getCode()
                    || status == OrderStatus.BIZ_FINISH_ORDER.getCode() || status == OrderStatus.CONFIRM_REFUND.getCode()
                    || status == OrderStatus.REFUSD_REFUND.getCode() || status == OrderStatus.CANCEL_NOT_REFUND.getCode())){
                order.setStatus(status);
                order.setUpdateTime(new DateTime());

                userOrderService.insertByUserOrder(order);
                return success(order,"订单操作成功");
            }else{
                return fail("订单操作失败");
            }
        }catch (Exception e){
            return fail("订单操作失败");
        }


    }

    /**
     * 订单支付
     * @throws IOException
     */
    @RequestMapping(value="/orderPay")
    @ResponseBody
    public Map<String, Object> ordersPay(
            @RequestParam(value = "orderId",required = true) String orderId,
            @RequestParam(value = "userId",required = true) Integer userId,
            @RequestParam(value = "payType",required = true) Integer payType,
            @RequestParam(value = "payFor",required = false) String payFor) throws IOException{

        String payParam = userOrderService.ordersPay(orderId,userId,payType,payFor);
        Map<String,String> map = new HashMap<>();

        map.put("payParam",payParam);
        return  success(payParam,"支付订单生成");
    }

    /**
     * 添加退款
     * @param orderId
     * @param descn  ByUserOrderInfoBvo order =
     * @return
     */
    @RequestMapping(value = "/submitRefund")
    @ResponseBody
    public Map<String, Object> submitRefund(@RequestParam(value = "orderId",required = false) Integer orderId,
                               @RequestParam(value = "descn",required = false) String descn) {
        try{
            ByUserOrder byUserOrder = userOrderService.findByUserOrder(orderId);
            byUserOrder.setRefundDesn(descn);
            byUserOrder.setStatus(4);
            userOrderService.insertByUserOrder(byUserOrder);

            return success(byUserOrder,"退款申请成功");
        }catch (Exception e){
            return fail("退款申请失败");
        }

    }

    /**
     * 退款详情
     * @param orderId
     * @return
     */
    @RequestMapping(value = "/getRefund")
    @ResponseBody
    public Map<String, Object> getRefund(@RequestParam(value = "orderId",required = false) Integer orderId) {
        try{
            Map<String, Object> map = new HashMap<>();
            ByUserOrderInfoBvo order = new ByUserOrderInfoBvo();
            order.setId(orderId);
            List<ByUserOrderInfoBvo> list = userOrderService.selectOrderListByPage(null,null,null,null,null,null,null,null,order,null,0, 1);
            order = null;
            if(list != null && list.size() > 0){
                order = list.get(0);
            }
            if(order == null){
                return fail("退款查询失败");
            }
            BigDecimal price = new BigDecimal("0.0");
            if(order.getPayStatus() == OrderPayStatus.PAY_ALL.getCode()){
                price = order.getPrice();
            }else if(order.getPayStatus() == OrderPayStatus.PAY_DEPOSIT.getCode()){
                price = order.getDeposit();
            }
            map.put("bizName",order.getBizUser().getCnName());
            map.put("refund",order.getRefundDesn());
            map.put("status",order.getStatus());
            map.put("price",price);
            return success(map,"退款查询成功");
        }catch (Exception e){
            return fail("退款查询失败");
        }

    }

    /**
     * 添加评论
     * @param order_id
     * @param user_stars
     * @param descn
     * @return
     */
    @RequestMapping(value = "/submitOrderComment")
    @ResponseBody
    public Map<String, Object> submitOrderComment(@RequestParam(value = "orderId",required = false) Integer order_id,
                                     @RequestParam(value = "userStars",defaultValue = "5") Integer user_stars,
//                                     @RequestParam(value = "file",required = false) MultipartFile file,
                                     @RequestParam(value = "descn",required = false) String descn) {
        try {
            ByUserOrder byUserOrder = userOrderService.findByUserOrder(order_id);
            byUserOrder.setUserStars(user_stars);
            byUserOrder.setUserComment(descn);
            byUserOrder.setEvaluationTime(new DateTime());
//            if (file != null && file.getSize() > 0) {
//                if (file.getSize() > 10000000) {
//                    throw new Exception("上传失败：文件大小不能超过10M");
//                }
//
//                String fileName = file.getOriginalFilename();
//                int indexdot = fileName.lastIndexOf(".");
//                String img_url = MD5Util.Md5(System.currentTimeMillis() + RandCharUtil.getRandStr(8) + MD5Util.Md5(file.getOriginalFilename())) + fileName.substring(indexdot);
//
////                FileUtil.saveFile(file.getInputStream(), PropertiesConfig.getProperty("img_upload_path", "/home")+"/"+img_url);
//                UploadUtil.uploadData(file.getBytes(), img_url);
//                byUserOrder.setImgUrl(img_url);
//            }
            byUserOrder.setStatus(9);
            userOrderService.insertByUserOrder(byUserOrder);
            return success(byUserOrder,"评论成功");
        }catch (Exception e){
            e.printStackTrace();
            return fail("评论失败");
        }

    }

    @RequestMapping(value = "/orderEvaluationList")
    @ResponseBody
    public Map<String, Object> getCommentList(ByUserOrder userOrder, RequestPage requestPage) {
        try{
            requestPage = requestPage == null ? new RequestPage() : requestPage;
            userOrder.setUserStarStart(userOrder.getUserStars());
            userOrder.setUserStarEnd(userOrder.getUserStars());
            if(null != userOrder.getPhone()){
                String[] phoneArr = userOrder.getPhone().split(",");
                for(String phone : phoneArr){

                }
            }
            List<ByUserOrderEvaluatvo> commentList = userOrderService.selectOrderListByBizUserOfEvaluation(userOrder, requestPage.getStart(), requestPage.getPageSize());
            userOrder.setFindFlag(2);
            int total = userOrderService.selectOrderListByBizUserCountzOfEvalution(userOrder);
            ResultPage<ByUserOrderEvaluatvo> evaluatvoResultPage = new ResultPage<ByUserOrderEvaluatvo>(total, requestPage.getPageSize(), commentList);
            return success(evaluatvoResultPage,"查询评论成功");
        }catch (Exception e){
            return fail("查询评论失败");
        }
    }

    @RequestMapping(value = "/getUserMessagePage")
    @ResponseBody
    public Map<String, Object> getUserMessagePage(@RequestParam(value = "userId") Integer userId, RequestPage requestPage) {
        try{
            requestPage = requestPage == null ? new RequestPage() : requestPage;
            List<ByUserMessage> messageList = userService.selectUserMessageByPage(userId, requestPage);
            ResultPage<ByUserMessage> messagePage = new ResultPage<ByUserMessage>(requestPage.getTotal(), requestPage.getPageSize(), messageList);
            return success(messagePage,"查询用户消息成功");
        }catch (Exception e){
            return fail("查询用户消息失败");
        }
    }

    @RequestMapping(value = "/deleteUserMessage")
    @ResponseBody
    public Map<String, Object> deleteUserMessage(@RequestParam(value = "id",required = false) Integer id) {

        try{
            userService.deleteByUserMessageKey(id);
            return success(id,"删除消息成功");
        }catch (Exception e){
            return fail("删除消息失败");
        }

    }

    @RequestMapping(value = "/addUserMessage")
    @ResponseBody
    public Map<String, Object> addUserMessage(ByUserMessage userMessage) {

        try{
            if(userMessage != null){
                userMessage.setCreateTime(new DateTime(Calendar.getInstance()));
                userService.insertUserMessage(userMessage);
                return success(userMessage,"新增消息成功");
            }else{
                return fail("新增消息失败");
            }
        }catch (Exception e){
            e.printStackTrace();
            return fail("新增消息失败");
        }

    }
}


